const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const log4js = require('./utils/log4j')

const users = require('./routes/users')
const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const koajwt = require('koa-jwt')
const util = require('./utils/util')

// error handler
onerror(app)

require('./config/db')

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
/*app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})*/
/*app.use(()=>{ //测试log4j的error日志写入
  ctx.body = 'hello'
})*/
app.use(async (ctx, next) => {
  log4js.info(`get params:${JSON.stringify(ctx.request.query)}`)
  log4js.info(`post params:${JSON.stringify(ctx.request.body)}`)
  //await next()
  await next().catch((err)=>{
    if (err.status == '401') {
      ctx.status = 200
      ctx.body = util.fail('Token认证失败',util.CODE.AUTH_ERROR)
    } else {
      throw err
    }
  })
})

// 所有接口都进入校验token是否有效
app.use(koajwt({sercret:'imooc'}).unless({
  path: [/^\/api\/users\/login/]
}))
// routes
// app.use(users.routes(), users.allowedMethods())
router.prefix("/api")

/*router.get('/leave/count',(ctx)=>{
  // const token = ctx.request.headers.authorization.split(' ')[1]
  // const payload = jwt.verify(token, 'imooc')
  // ctx.body = payload
  ctx.body = 'body'
})*/

router.use(users.routes(), users.allowedMethods())

app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  //console.error('server error', err, ctx)
  log4js.error(`${err.stack}`)
});

module.exports = app
